package com.yishun.springboot.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yishun.springboot.mapper.RoleMapper;
import com.yishun.springboot.mapper.UserMapper;
import com.yishun.springboot.pojo.User;
import com.yishun.springboot.service.UserService;
import com.yishun.springboot.util.PageHelper;
import com.yishun.springboot.util.ResultUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	UserMapper userDao;

	@Autowired
	RoleMapper roleDao;

	public void checkLogin(String username, String Password) {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, Password);
		subject.login(token);
	}

	public JSONArray getRoleAndPage() {
		// 获取当前用户的 Subject 对象
		Subject currentUser = SecurityUtils.getSubject();

		// 获取保存在 Session 中的用户信息
		User user = (User) currentUser.getSession().getAttribute("user");
		Set<Object> set = roleDao.getById(user.getUsername());
		List<Object> liststring = new ArrayList<Object>(set);
		List<Map<String, Object>> li = userDao.getRoleAndPage(String.valueOf(user.getUserId()), user.getUsername());
		List<Map<String, Object>> lis = userDao.findByRoleIdAndUserName(liststring, user.getUsername());
		JSONArray list = null;
		JSONArray lists = new JSONArray();
		JSONArray jsonArr = null;
		for (int i = 0; i <= li.size() - 1; i++) {
			Map<String, Object> map = li.get(i);
			list = new JSONArray();

			for (int y = 0; y <= li.size() - 1; y++) {
				Map<String, Object> mapVa = li.get(y);
				if ((Integer) map.get("page_id") == (Integer) mapVa.get("pagerank")) {
					jsonArr = new JSONArray();
					for (int f = 0; f <= lis.size() - 1; f++) {
						Map<String, Object> mapVal = lis.get(f);
						if ((Integer) mapVal.get("page_id") == (Integer) mapVa.get("page_id")) {
							jsonArr.add(mapVal);
						}
					}
					mapVa.put("menu", jsonArr);
					list.add(mapVa);
				}
			}
			map.put("children", list);
			if ((Integer) map.get("pagerank") == 0) {
				lists.add(map);
			}
		}
		return lists;
	}

	@Override
	public JSONObject getConditionInquire(JSONObject jsonObject) {
		Integer positionId = jsonObject.getInteger("positionId");// 职位id
		Integer departmentId = jsonObject.getInteger("departmentId");// 部门id
		String name = jsonObject.getString("name");// 人员姓名
		Integer pageNo = jsonObject.getInteger("pageNo");
		Integer pageSize = jsonObject.getInteger("pageSize");
		Integer userId = jsonObject.getInteger("userId");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("positionId", positionId);
		map.put("departmentId", departmentId);
		map.put("name", name);
		map.put("userId", userId);
		Integer count = userDao.getConditionInquireCount(map);
		PageHelper pageHelper = new PageHelper(count, pageSize, pageNo);
		map.put("pageNo", pageHelper.getOffset());
		map.put("pageSize", pageHelper.getLimit());
		return ResultUtils.jsonSuccess(userDao.getConditionInquire(map), pageHelper.getCurrentPage(), count);
	}

	@Override
	public JSONObject upTbUser(JSONObject jsonObject) {
		User user = JSON.parseObject(jsonObject.toJSONString(), User.class);
		if (user.getIdentitycard() != null && !user.getIdentitycard().equals("")) {
			LocalDate birthDate = getBirthDateFromIdCard(user.getIdentitycard());
			LocalDate today = LocalDate.now();
			user.setAge(calculateAge(birthDate, today));
		}
		Integer num = userDao.upTbUsers(user);
		if (num >= 1) {
			return ResultUtils.jsonSuccessNotData("修改成功");
		} else {
			return ResultUtils.jsonFail("修改失败，请联系管理员");
		}
	}

	public JSONObject delUser(JSONObject jsonObject) {
		Map<String, Object> map = new HashMap<>();
		map.put("userId", jsonObject.getInteger("userId"));
		String username = userDao.getConditionInquire(map).get(0).get("username").toString();
		Integer num = userDao.delUser(jsonObject.getInteger("userId"));

		num += userDao.delPageRole(username);
		num += userDao.delRolesPermission(username);// 删除了此账号就需要再继续删除归属于他自身的所有权限
		num += userDao.delUserMenu(username);
		if (num >= 1) {
			return ResultUtils.jsonSuccess();
		}
		return ResultUtils.jsonFail(505);
	}

	@Override
	public JSONObject addUser(JSONObject jsonObject) {
		User user = JSON.parseObject(jsonObject.toJSONString(), User.class);
		LocalDate birthDate = getBirthDateFromIdCard(user.getIdentitycard());
		LocalDate today = LocalDate.now();
		user.setAge(calculateAge(birthDate, today));
		user.setPassword(user.getIdentitycard().substring(12));
		Integer num = userDao.addUser(user);
		if (num >= 1) {
			return ResultUtils.jsonSuccess();
		}
		return ResultUtils.jsonFail(400);
	}

	public static LocalDate getBirthDateFromIdCard(String idCard) {
		String birthDateString = idCard.substring(6, 14); // 身份证号中的出生年月日部分
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
		return LocalDate.parse(birthDateString, formatter);
	}

	// 计算年龄
	public static int calculateAge(LocalDate birthDate, LocalDate today) {
		return birthDate.until(today).getYears();
	}

	@Override
	public JSONObject importUsers(MultipartFile file) {
		int sheets = 0;
		List<User> li = new ArrayList<>();
		try {
			Workbook workbook = convertMultipartFileToWorkbook(file);
			// 有多少个sheet
			sheets = workbook.getNumberOfSheets();
			for (int i = 0; i < sheets; i++) {
				Sheet sheet = workbook.getSheetAt(i);
				// 获取多少行
				int rows = sheet.getPhysicalNumberOfRows();
				// 遍历每一行，注意：第 0 行为标题
				for (int j = 1; j < rows; j++) {
					// 获得第 j 行
					Row row = sheet.getRow(j);

					// 获取单元格
					Cell cell1 = row.getCell(0);
					Cell cell2 = row.getCell(1);
					Cell cell3 = row.getCell(2);
					Cell cell4 = row.getCell(3);
					Cell cell5 = row.getCell(4);
					Cell cell6 = row.getCell(5);
					Cell cell7 = row.getCell(6);
					Cell cell8 = row.getCell(7);
					Cell cell9 = row.getCell(8);
					cell1.setCellType(CellType.STRING);
					cell2.setCellType(CellType.STRING);
					cell3.setCellType(CellType.STRING);
					cell4.setCellType(CellType.STRING);
					cell5.setCellType(CellType.STRING);
					cell6.setCellType(CellType.STRING);
					cell7.setCellType(CellType.STRING);
					cell8.setCellType(CellType.STRING);
					cell9.setCellType(CellType.STRING);
					User user = new User();
					user.setUsername(cell1.getStringCellValue());
					user.setName(cell2.getStringCellValue());
					user.setPhone(cell3.getStringCellValue());
					user.setSex(cell4.getStringCellValue());
					user.setIdentitycard(cell5.getStringCellValue());
					LocalDate birthDate = getBirthDateFromIdCard(cell5.getStringCellValue());
					LocalDate today = LocalDate.now();
					user.setAge(calculateAge(birthDate, today));
					user.setDepartment_id(Integer.valueOf(cell6.getStringCellValue()));
					user.setPosition_id(Integer.valueOf(cell7.getStringCellValue()));
					user.setLocation(cell8.getStringCellValue());
					user.setWeChat(cell9.getStringCellValue());
					user.setPassword(user.getIdentitycard().substring(12));
					li.add(user);
				}
			}
			Integer num = userDao.addUsers(li);
			if (num >= 1) {
				return ResultUtils.jsonSuccess();
			}
			return ResultUtils.jsonFail(505);
		} catch (IOException e) {
			return ResultUtils.jsonFail(505);
		}
	}

	public static Workbook convertMultipartFileToWorkbook(MultipartFile file) throws IOException {
		try (InputStream inputStream = file.getInputStream()) {
			return WorkbookFactory.create(inputStream);
		} catch (IOException e) {
			// 处理异常，比如日志记录或者抛出自定义异常
			throw new RuntimeException("Failed to convert MultipartFile to Workbook", e);
		} catch (EncryptedDocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
